package com.qf.service.impl;

import cn.hutool.core.util.StrUtil;
import com.qf.entity.SysPermission;
import com.qf.entity.SysRoleEntity;
import com.qf.entity.SysUser;
import com.qf.mapper.UserMapper;
import com.qf.service.IUserService;
import com.qf.utils.JwtUtils;
import com.qf.utils.RsaUtils;
import com.qf.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.security.PrivateKey;
import java.util.List;
import java.util.stream.Collectors;

@Service
@SuppressWarnings("all")
public class UserService implements IUserService {
    @Autowired
    private UserMapper mapper;


    @Override
    public ResultVO findByPN(SysUser sysUser) {
        if (sysUser == null) {
            return new ResultVO(false, "账户或密码错误");
        }
        SysUser byNP = mapper.findByNP(sysUser.getUserName());
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (byNP == null ||!bCryptPasswordEncoder.matches(sysUser.getPassword(), byNP.getPassword())) {
            return new ResultVO(false, "账户或密码错误");
        }

        List<SysRoleEntity> roles = mapper.findRoles(byNP.getUserId() + "");
        List<String> collect = roles.stream().map(role -> role.getRoleName()).collect(Collectors.toList());

        List<SysPermission> permission = mapper.findPermission(byNP.getUserId() + "");
        List<String> collect1 = permission.stream().map(permiss -> permiss.getPermName()).collect(Collectors.toList());

        byNP.setPermissions(StrUtil.join(",", collect1));
        byNP.setRoles(StrUtil.join(",", collect));

        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(ResourceUtils.getFile("classpath:rsa.pri").getPath());
            String token = JwtUtils.generateTokenExpireInMinutes(byNP, privateKey, 100);
            return new ResultVO(true,"登陆成功",token);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultVO(false, "账户或密码错误");
        }
    }
}
